package com.uphone.kingmall.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uphone.kingmall.adapter.SearchGoodsListAdapter;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.GoodsListBean;
import com.uphone.kingmall.listener.NetListCallBack;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.intent.IntentData;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索商品列表页面
 */
public class SearchGoodsListActivity0 extends BaseActivity implements AMapLocationListener {
    @BindView(R.id.listViewRV)
    RecyclerView listViewRV;
    @BindView(R.id.iv_fanhui)
    ImageView ivFanhui;
    @BindView(R.id.et_title_sousuo)
    EditText tvTitleSousuo;
    @BindView(R.id.radio_1)
    RadioButton radio1;
    @BindView(R.id.radio_2)
    RadioButton radio2;
    @BindView(R.id.radio_3)
    RadioButton radio3;
    @BindView(R.id.radio_4)
    RadioButton radio4;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
//    @BindView(R.id.goods_list_resfresh)
//    TwinklingRefreshLayout goodsListResfresh;

    @BindView(R.id.iv_list_type)
    ImageView ivListType;
    int page = 1;
    @IntentData
    int id = -1;
    private SearchGoodsListAdapter searchGoodsListAdapter;
    private List<GoodsListBean.DataBean> dataList = new ArrayList<>();
    //    private boolean isLoad = false;
    private String orderby = "1";

    @Override
    public void initData() {
        GridLayoutManager manager = new GridLayoutManager(getApplicationContext(), 1);

        listViewRV.setLayoutManager(manager);
//        listViewRV.addItemDecoration(new SpacesItemDecoration(5,5,getResources().getColor(R.color.colorTransparent)));
        searchGoodsListAdapter = new SearchGoodsListAdapter(this, listViewRV, manager);
        listViewRV.setAdapter(searchGoodsListAdapter);

        loadData(1, "1");

        initListener();
    }

    private void initListener() {

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                loadData(1, orderby);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                loadData(++page, orderby);
            }
        });

        searchGoodsListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CommonUtil.startIntent(SearchGoodsListActivity0.this, GoodsDetailActivity.class, dataList.get(position).getGoodsId());
            }
        });
        tvTitleSousuo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                loadData(1, orderby);
            }
        });

    }


    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_search_goods_list;
    }

    @Override
    public void initView() {
//        mImmersionBar
//                .statusBarColor(R.color.colorWhite)
//                .statusBarDarkFont(true, 0.2f)
//                .navigationBarColor(R.color.black)
//                .fullScreen(false)
//                .init();
        setStatusBar();
        loadPermission();
    }

    @OnClick({R.id.iv_fanhui, R.id.radio_1, R.id.radio_2, R.id.radio_3, R.id.radio_4, R.id.iv_list_type, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_fanhui:
                KeyboardUtils.hideSoftInput(this);
                onBackPressed();
                break;
            case R.id.radio_1://默认
                loadData(1, "1");

                break;
            case R.id.radio_2://价格
                loadData(1, "2");

                break;
            case R.id.radio_3://人气
                loadData(1, "3");

                break;
            case R.id.radio_4://筛选
                loadData(1, "4");

                break;
            case R.id.iv_list_type://类型

                int type = searchGoodsListAdapter.switchType();
                if (type == 0) {
                    ivListType.setSelected(true);
                } else {
                    ivListType.setSelected(false);
                }

                break;
            case R.id.tv_search:

                break;
        }
    }


    private void loadData(int page, String orderby) {
//        if (isLoad) {
//            return;
//        }
//        isLoad = true;
        this.page = page;
        this.orderby = orderby;
        HttpParams params = new HttpParams();
        LogUtils.e("orderby:" + orderby);
        if (TextUtils.equals("4", orderby)) {
            // 经纬度
            LogUtils.e("latLng:" + latLng);
            if (latLng != null) {
                params.put("lonlat", latLng.longitude + "," + latLng.latitude);
            }
        }
        params.put("page", page + "");
        params.put("limit", "10");
        if (TextUtils.isEmpty(tvTitleSousuo.getText())) {
            params.put("keyword", "");
        } else {
            params.put("keyword", tvTitleSousuo.getText().toString().trim());
        }
        if (id != -1) {
            params.put("shopId", id);
        }
        params.put("orderby", orderby);
        params.put("asc", "2");
        CommonUtil.netRv(new GoodsListBean(), searchGoodsListAdapter, dataList, MyUrl.searchGoods, params, page, new NetListCallBack<GoodsListBean.DataBean>() {
            @Override
            public void callBack(List<GoodsListBean.DataBean> list) {
//                isLoad = false;
                dataList = list;
                if (dataList == null || dataList.size() == 0) {
                    tvEmpty.setVisibility(View.VISIBLE);
                } else {
                    tvEmpty.setVisibility(View.GONE);
                }
            }
        });

    }


    private LatLng latLng;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private static final int PERMISSION_REQUEST_MY_REQUEST = 3;

    private void loadPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_SETTINGS);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (!permissionList.isEmpty()) {  //申请的集合不为空时，表示有需要申请的权限
                requestPermissions(permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQUEST_MY_REQUEST);
            } else { //所有的权限都已经授权过了
                initLocation();
            }
        } else {
            initLocation();
        }

    }

    /**
     * 如果AMapLocationClient是在当前Activity实例化的，
     * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mLocationClient.stopLocation();
            }
        } else {
            LogUtils.e("定位失败");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            if (requestCode == PERMISSION_REQUEST_MY_REQUEST) {
                // 定位权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                } else {
                    com.blankj.utilcode.util.ToastUtils.showShort("没有开启定位权限，定位失败");
                    DialogUtil.openAppDetails(this, "定位");
                }
            }
        }
    }

}
